﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using P2P_Backup.archive;
using System.Xml;

namespace P2P_Backup
{
    public static class Storage
    {
        public static string filePath;
        public static P2PBackup load(String filePath)
        {
            Storage.filePath = filePath;
            if (System.IO.File.Exists(filePath))
            {
                FileStream fs = new FileStream(filePath, FileMode.Open);
                try
                {
                    XmlSerializer ser = new XmlSerializer(typeof(P2PBackup));
                    P2PBackup result = (P2PBackup)ser.Deserialize(fs);
                    return result;
                }
                catch
                {
                    Console.WriteLine("Could not read " + filePath);
                }
                finally
                {
                    fs.Close();
                }
            }
            else
            {
                return null;
            }

            return null;
        }

        public static Boolean save(P2PBackup instance, String filePath)
        {
            Storage.filePath = filePath;
            return save(instance);
        }
        public static Boolean save(P2PBackup instance)
        {
            if (filePath != null)
            {
                XmlSerializer ser = new XmlSerializer(typeof(P2PBackup));
                FileStream fs = new FileStream(filePath, FileMode.Create);
                ser.Serialize(fs, instance);
                fs.Close();
                if (System.IO.File.Exists(filePath))
                { return true; }
                else
                { return false; }
            }
            return false;
        }
        public static String GetRestoreXML(Folder folder)
        {
            XmlSerializer ser = new XmlSerializer(typeof(Folder));
            StringBuilder stringBuilder = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(stringBuilder);
            ser.Serialize(writer, folder);
            return stringBuilder.ToString();
        }
        public static Folder GetRestoreFolder(Stream stream)
        {
            XmlSerializer ser = new XmlSerializer(typeof(Folder));
            stream.Position = 0;
            TextReader reader = new StreamReader(stream);
            Folder folder = (Folder)ser.Deserialize(reader);
            return folder;
        }
    }
}
